import React, { useState, useEffect } from 'react' // 导入React核心库和必要的hooks
import { useNavigate, useParams, useSearchParams } from 'react-router-dom' // 导入React Router相关hooks // 导入样式文件
import './details.css'

// 医生详情数据接口
interface DoctorDetail {
  id: string
  name: string
  title: string
  department: string
  hospital: string
  avatar: string
  isFollowed: boolean
  stats: {
    views: number
    rating: number
    responseTime: string
    followers: number
  }
  expertise: string
  services: {
    onlineConsultation: boolean
    prescriptionRefill: boolean
    preferredPharmacy: boolean
    clinicAppointment: boolean
  }
  reviews: Array<{
    id: string
    user: string
    rating: number
    tags: string[]
    content: string
    reply: string
    timestamp: string
  }>
  consultationRecords: Array<{
    id: string
    user: string
    service: string
    timestamp: string
  }>
}

/**
 * 医生详情页面组件
 * 展示医生个人信息、服务、评价等内容，支持关注、评论和回复功能
 */
/**
 * 医生详情页面组件
 * 展示医生个人信息、服务、评价等内容，并提供关注、咨询等交互功能
 */
function Index() {

  // 导航相关hooks
  const navigate = useNavigate() // 用于页面导航
  const { id } = useParams() // 获取URL中的医生ID参数
  const [searchParams] = useSearchParams() // 获取URL查询参数
  const [doctor, setDoctor] = useState<DoctorDetail | null>(null) // 医生详情状态
  const [loading, setLoading] = useState(true) // 加载状态
  const [showCommentForm, setShowCommentForm] = useState(false) // 控制评论表单显示 // 新评论表单数据
  const [newComment, setNewComment] = useState({
    rating: 5,
    content: '',
    tags: [] as string[]
  })
  const [activeReplyId, setActiveReplyId] = useState<string | null>(null) // 当前激活的回复ID
  const [replyContent, setReplyContent] = useState('') // 回复内容
  const [isExpertiseExpanded, setIsExpertiseExpanded] = useState(false) // 控制专长描述展开/收起

  // 模拟医生详情数据
  useEffect(() => {
    // 从URL参数获取医生信息
    const name = searchParams.get('name') || '涂晓瑜'
    const avatar = searchParams.get('avatar') || '/default-avatar.png'
    const title = searchParams.get('title') || '主治医师'
    const dept = searchParams.get('dept') || '妇科'
    const hospital = searchParams.get('hospital') || '东莞市第八人民医院 (东莞市儿童医院)'
    const specialty = searchParams.get('specialty') || '擅长对妇产科常见病、多发病的治疗,特别是妇科内分泌疾患(多囊卵巢综合症、更年期综合症、更年期综合征),月经失调,异...'
    
    // 检查该医生是否已被关注
    const savedDoctors = localStorage.getItem('followedDoctors')
    let isFollowed = false
    if (savedDoctors) {
      try {
        const followedDoctors = JSON.parse(savedDoctors)
        const existingDoctor = followedDoctors.find((d: { name: string }) => d.name === name)
        isFollowed = !!existingDoctor
      } catch (error) {
        console.error('解析关注的医生数据失败:', error)
        isFollowed = false
      }
    }
    
    const mockDoctor: DoctorDetail = {
      id: '1',
      name: name,
      title: title,
      department: dept,
      hospital: hospital,
      avatar: avatar,
      isFollowed: isFollowed,
      stats: {
        views: 11942,
        rating: 99,
        responseTime: '2小时',
        followers: 6801
      },
      expertise: specialty,
      services: {
        onlineConsultation: true,
        prescriptionRefill: true,
        preferredPharmacy: true,
        clinicAppointment: false
      },
      reviews: [
        {
          id: '1',
          user: '广西百色用户**',
          rating: 5,
          tags: ['态度非常好', '回复很及时', '语气很温和', '讲解很细致'],
          content: '医生很专业，态度也很好，解答很详细，非常感谢！',
          reply: '感谢涂晓瑜医生的回复~',
          timestamp: '2023-02-18 00:20:02'
        },
        {
          id: '2',
          user: '辽宁沈阳用户**',
          rating: 5,
          tags: ['态度非常好', '回复很及时', '语气很温和'],
          content: '医生回复很及时，专业水平很高，推荐！',
          reply: '',
          timestamp: '2023-02-17 15:30:45'
        }
      ],
      consultationRecords: [
        {
          id: '1',
          user: '广东珠海ms35Qj0kW3',
          service: '图文咨询服务',
          timestamp: '2023-02-18 10:15:30'
        },
        {
          id: '2',
          user: '广东东莞msYZDGxz8b',
          service: '图文咨询服务',
          timestamp: '2023-02-18 09:45:20'
        }
      ]
    }
    
    // 尝试从localStorage恢复评论数据
    const doctorKey = `doctor_comments_${name}`
    const savedComments = localStorage.getItem(doctorKey)
    if (savedComments) {
      try {
        const parsedComments = JSON.parse(savedComments)
        // 合并默认评论和保存的评论，避免重复
        const defaultCommentIds = new Set(mockDoctor.reviews.map(c => c.id))
        const newComments = parsedComments.filter((c: any) => !defaultCommentIds.has(c.id))
        mockDoctor.reviews = [...newComments, ...mockDoctor.reviews]
        console.log(`已恢复医生 ${name} 的评论数据:`, newComments.length, '条新评论')
      } catch (error) {
        console.error('解析保存的评论数据失败:', error)
      }
    }
    
    // 调试日志
    console.log(`医生 ${name} 的关注状态:`, isFollowed)
    
    setDoctor(mockDoctor)
    setLoading(false)
  }, [id, searchParams])

  // 页面卸载时保存评论数据
  useEffect(() => {
    const handleBeforeUnload = () => {
      if (doctor && doctor.reviews.length > 0) {
        // 检查是否有新的评论数据需要保存
        const doctorKey = `doctor_comments_${doctor.name}`
        const savedComments = localStorage.getItem(doctorKey)
        if (savedComments) {
          try {
            const parsedComments = JSON.parse(savedComments)
            // 如果当前评论数量与保存的不同，说明有更新
            if (parsedComments.length !== doctor.reviews.length) {
              syncCommentsToStorage(doctor.reviews)
            }
          } catch (error) {
            console.error('检查评论数据更新失败:', error)
          }
        }
      }
    }

    window.addEventListener('beforeunload', handleBeforeUnload)
    
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload)
    }
  }, [doctor])

  // 监听关注状态变化，实时同步
  useEffect(() => {
    const handleFollowedDoctorsChanged = () => {
      if (doctor) {
        const savedDoctors = localStorage.getItem('followedDoctors')
        if (savedDoctors) {
          try {
            const followedDoctors = JSON.parse(savedDoctors)
            const isCurrentlyFollowed = followedDoctors.some((d: { id: string }) => d.id === doctor.id)
            
            // 如果关注状态发生变化，更新本地状态
            if (isCurrentlyFollowed !== doctor.isFollowed) {
              setDoctor(prev => prev ? { ...prev, isFollowed: isCurrentlyFollowed } : null)
              console.log(`医生 ${doctor.name} 的关注状态已同步:`, isCurrentlyFollowed)
            }
          } catch (error) {
            console.error('同步关注状态失败:', error)
          }
        }
      }
    }

    window.addEventListener('followedDoctorsChanged', handleFollowedDoctorsChanged)
    
    return () => {
      window.removeEventListener('followedDoctorsChanged', handleFollowedDoctorsChanged)
    }
  }, [doctor])

  // 同步评论数据到localStorage的辅助函数
  const syncCommentsToStorage = (comments: any[]) => {
    if (!doctor) return
    
    try {
      const doctorKey = `doctor_comments_${doctor.name}`
      localStorage.setItem(doctorKey, JSON.stringify(comments))
      console.log(`评论数据已同步到localStorage:`, comments.length, '条评论')
    } catch (error) {
      console.error('同步评论数据到localStorage失败:', error)
    }
  }

  // 清理评论数据的函数
  const handleClearComments = () => {
    if (!doctor) return
    
    if (window.confirm('确定要清理所有评论数据吗？此操作不可恢复。')) {
      try {
        const doctorKey = `doctor_comments_${doctor.name}`
        localStorage.removeItem(doctorKey)
        
        // 重置为默认评论
        const defaultReviews = [
          {
            id: '1',
            user: '广西百色用户**',
            rating: 5,
            tags: ['态度非常好', '回复很及时', '语气很温和', '讲解很细致'],
            content: '医生很专业，态度也很好，解答很详细，非常感谢！',
            reply: '感谢涂晓瑜医生的回复~',
            timestamp: '2023-02-18 00:20:02'
          },
          {
            id: '2',
            user: '辽宁沈阳用户**',
            rating: 5,
            tags: ['态度非常好', '回复很及时', '语气很温和'],
            content: '医生回复很及时，专业水平很高，推荐！',
            reply: '',
            timestamp: '2023-02-17 15:30:45'
          }
        ]
        
        setDoctor({
          ...doctor,
          reviews: defaultReviews
        })
        
        showToast('评论数据已清理')
        console.log('评论数据已清理')
      } catch (error) {
        console.error('清理评论数据失败:', error)
        showToast('清理评论数据失败')
      }
    }
  }

/**
 * 处理医生关注/取消关注的函数
 * 该函数会更新医生的关注状态，并同步到localStorage中
 * 同时会触发自定义事件通知其他组件关注列表已更新
 */
  const handleFollow = () => {
  // 确保医生对象存在
    if (doctor) {
    // 更新医生对象中的关注状态
      const newFollowState = !doctor.isFollowed
      setDoctor({
        ...doctor,
        isFollowed: newFollowState
      })
      
      // 同步关注状态到localStorage
      const savedDoctors = localStorage.getItem('followedDoctors')
      let followedDoctors = savedDoctors ? JSON.parse(savedDoctors) : []
      
      if (newFollowState) {
        // 添加医生到关注列表
        const doctorToAdd = {
          id: doctor.id,
          name: doctor.name,
          avatar: doctor.avatar,
          title: doctor.title,
          department: doctor.department,
          hospital: doctor.hospital,
          rating: doctor.stats.rating,
          isFollowed: true,
          lastMessage: '点击开始问诊',
          lastMessageTime: new Date().toLocaleString('zh-CN')
        }
        
        // 检查是否已经存在
        const exists = followedDoctors.find((d: { id: string }) => d.id === doctor.id)
        if (!exists) {
          followedDoctors.push(doctorToAdd)
          localStorage.setItem('followedDoctors', JSON.stringify(followedDoctors))
          console.log(`医生 ${doctor.name} 已添加到关注列表`)
          
          // 触发自定义事件，通知其他组件数据已更新
          window.dispatchEvent(new CustomEvent('followedDoctorsChanged'))
          
          // 显示成功提示
          showToast('关注成功，可在"我的医生"页面查看')
          showFollowAnimation(true) // 添加关注成功动画
        } else {
          showToast('该医生已在关注列表中')
        }
      } else {
        // 从关注列表中移除
        followedDoctors = followedDoctors.filter((d: { id: string }) => d.id !== doctor.id)
        localStorage.setItem('followedDoctors', JSON.stringify(followedDoctors))
        console.log(`医生 ${doctor.name} 已从关注列表移除`)
        
        // 触发自定义事件，通知其他组件数据已更新
        window.dispatchEvent(new CustomEvent('followedDoctorsChanged'))
        
        // 显示成功提示
        showToast('已取消关注')
      }
    }
  }

/**
 * 处理发送消息的函数
 * 当用户选择医生后，将医生信息保存到本地存储中，并导航到消息页面
 */
  // 检查是否存在医生对象
  const handleSendMessage = () => {
    if (doctor) {
      const selectedDoctor = {
        id: Number(doctor.id) || 0,
        name: doctor.name,
        title: doctor.title,
        hospital: doctor.hospital,
        specialty: doctor.expertise,
      }
      localStorage.setItem('selectedDoctor', JSON.stringify(selectedDoctor))
    }
    navigate('/message')
  }



  // 显示评论表单
  const handleShowCommentForm = () => {
    setShowCommentForm(true)
  }

  // 隐藏评论表单
  const handleHideCommentForm = () => {
    setShowCommentForm(false)
    setNewComment({
      rating: 5,
      content: '',
      tags: []
    })
  }

  // 处理评分变化
  const handleRatingChange = (rating: number) => {
    setNewComment(prev => ({ ...prev, rating }))
  }

  // 处理标签选择
/**
 * 处理标签切换的函数
 * 当用户点击标签时，如果标签已存在则移除，不存在则添加
 * @param {string} tag - 需要切换的标签
 */
  const handleTagToggle = (tag: string) => {
    // 保留之前的所有属性
    setNewComment(prev => ({
      ...prev,
      tags: prev.tags.includes(tag)
        ? prev.tags.filter(t => t !== tag)
        : [...prev.tags, tag]
    }))
  }

  // 提交评论
/**
 * 提交评论的处理函数
 * 该函数用于创建新评论并将其添加到医生评论列表中
 */
  const handleSubmitComment = () => {
  // 检查评论内容是否为空，如果为空则直接返回
    if (!newComment.content.trim()) return

  // 创建评论对象，包含评论的各种信息
    const comment = {
      id: Date.now().toString(), // 使用当前时间戳作为评论ID
      user: '当前用户**',
      rating: newComment.rating, // 评分
      tags: newComment.tags,    // 标签
      content: newComment.content, // 评论内容
      reply: '',               // 回复内容（初始为空）
      timestamp: new Date().toLocaleString('zh-CN') // 评论时间（中文格式）
    }

  // 如果医生信息存在，则更新医生的评论列表
    if (doctor) {
      const updatedReviews = [comment, ...doctor.reviews]
      setDoctor({
        ...doctor,
        reviews: updatedReviews
      })
      
      // 同步评论数据到localStorage
      syncCommentsToStorage(updatedReviews)
    }

    // 重置表单
    setNewComment({
      rating: 5,
      content: '',
      
      tags: []
    })
    setShowCommentForm(false)
  }

  // 点击回复按钮
  /**
   * 处理回复点击事件的函数
   * @param reviewId - 要回复的评论ID
   */
  const handleReplyClick = (reviewId: string) => {
    // 设置当前活动回复的评论ID
    setActiveReplyId(reviewId)
    setReplyContent('')
  }

  // 提交回复
/**
 * 处理医生回复患者评价的函数
 * @param reviewId - 要回复的评价ID
 */
  const handleSubmitReply = (reviewId: string) => {
  // 检查回复内容是否为空或医生信息是否存在
    if (!replyContent.trim() || !doctor) return
    
    // 更新医生数据，添加回复
  // 使用map遍历所有评价，找到匹配的评价ID后添加回复
    const updatedReviews = doctor.reviews.map(review => {
      if (review.id === reviewId) {
        return {
          ...review,
          reply: replyContent.trim()  // 添加回复内容
        }
      }
      return review  // 保持其他评价不变
    })
    
  // 更新医生状态，包含新的回复数据
    setDoctor({
      ...doctor,
      reviews: updatedReviews
    })
    
    // 同步评论数据到localStorage
    syncCommentsToStorage(updatedReviews)
    
    // 显示成功提示
    showToast('回复成功')
    
    // 重置回复状态
    setActiveReplyId(null)  // 清除当前回复ID
    setReplyContent('')    // 清空回复内容
  }

  // 取消回复
  const handleCancelReply = () => {
    setActiveReplyId(null)
    setReplyContent('')
  }

  // 轻提示函数
  const showToast = (message: string) => {
    // 创建toast元素
    const toast = document.createElement('div')
    toast.className = 'toast-message'
    toast.textContent = message
    
    // 添加到页面
    document.body.appendChild(toast)
    
    // 显示动画
    setTimeout(() => {
      toast.classList.add('show')
    }, 10)

    // 自动隐藏
    setTimeout(() => {
      toast.classList.remove('show')
      setTimeout(() => {
        if (document.body.contains(toast)) {
          document.body.removeChild(toast)
        }
      }, 300)
    }, 2000)
  }

  // 关注成功动画
  const showFollowAnimation = (isFollowed: boolean) => {
    if (isFollowed) {
      // 创建关注成功动画元素
      const animation = document.createElement('div')
      animation.className = 'follow-animation'
      animation.innerHTML = `
        <div class="animation-content">
          <span class="animation-icon">✓</span>
          <span class="animation-text">关注成功</span>
        </div>
      `
      
      // 添加到页面
      document.body.appendChild(animation)
      
      // 显示动画
      setTimeout(() => {
        animation.classList.add('show')
      }, 10)

      // 自动隐藏
      setTimeout(() => {
        animation.classList.remove('show')
        setTimeout(() => {
          if (document.body.contains(animation)) {
            document.body.removeChild(animation)
          }
        }, 300)
      }, 1500)
    }
  }

  if (loading) {
    return (
      <div className="loading-container">
        <div className="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    )
  }

  if (!doctor) {
    return (
      <div className="error-container">
        <p>医生信息不存在</p>
      </div>
    )
  }

  return (
    <div className="doctor-detail-page">
      {/* 顶部导航栏 */}
      <div className="top-nav">
        <button className="back-btn" onClick={() => navigate(-1)}>
          <span>&lt;</span>
        </button>
        <h1 className="page-title">妙手医生网络诊室</h1>
      </div>

      {/* 医生信息卡片 */}
      <div className="doctor-info-card">
        <div className="doctor-profile">
          <div className="avatar-container">
            <img 
              src={doctor.avatar} 
              alt={doctor.name} 
              className="doctor-avatar"
              onError={(e) => {
                // 如果本地头像也失败，使用内联SVG作为备用
                const target = e.currentTarget;
                target.style.display = 'none';
                
                // 创建SVG备用头像
                const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
                svg.setAttribute('width', '80');
                svg.setAttribute('height', '80');
                svg.setAttribute('viewBox', '0 0 80 80');
                svg.innerHTML = `
                  <circle cx="40" cy="40" r="40" fill="#4A90E2"/>
                  <circle cx="40" cy="25" r="15" fill="white"/>
                  <rect x="25" y="40" width="30" height="25" rx="3" fill="white"/>
                  <rect x="35" y="50" width="10" height="15" fill="#4A90E2"/>
                  <rect x="33" y="52" width="14" height="11" fill="#4A90E2"/>
                `;
                svg.style.borderRadius = '50%';
                svg.style.border = '3px solid #e8f4fd';
                
                target.parentNode?.appendChild(svg);
              }}
            />
          </div>
          <div className="doctor-basic-info">
            <h2 className="doctor-name">{doctor.name}</h2>
            <div className="doctor-title">
              <span>{doctor.title}</span>
              <span className="divider">|</span>
              <span>{doctor.department}</span>
            </div>
            <p className="hospital-name">{doctor.hospital}</p>
          </div>
          <button 
            className={`follow-btn ${doctor.isFollowed ? 'followed' : ''}`}
            onClick={handleFollow}
          >
            <span className="follow-icon">{doctor.isFollowed ? '✓' : '+'}</span>
            {doctor.isFollowed ? '已关注' : '关注'}
          </button>
          
          {/* 快速跳转到我的医生页面 */}
          {doctor.isFollowed && (
            <button 
              className="view-concern-btn"
              onClick={() => navigate('/concern')}
              title="查看我的医生"
            >
              👥 我的医生
            </button>
          )}
        </div>

        {/* 关键统计数据 */}
        <div className="doctor-stats">
          <div className="stat-item">
            <span className="stat-number">{doctor.stats.views}</span>
            <span className="stat-label">浏览人次</span>
          </div>
          <div className="stat-item">
            <span className="stat-number">{doctor.stats.rating}%</span>
            <span className="stat-label">好评率</span>
          </div>
          <div className="stat-item">
            <span className="stat-number">{doctor.stats.responseTime}</span>
            <span className="stat-label">平均响应</span>
          </div>
          <div className="stat-item">
            <span className="stat-number">{doctor.stats.followers}</span>
            <span className="stat-label">粉丝数</span>
          </div>
        </div>

        {/* 专长描述 */}
        <div className="expertise-section">
          <p className={`expertise-text ${isExpertiseExpanded ? 'expanded' : ''}`}>
            擅长: {doctor.expertise}
          </p>
          <button 
            className="view-profile-btn" 
            onClick={() => setIsExpertiseExpanded(!isExpertiseExpanded)}
          >
            {isExpertiseExpanded ? '收起' : '查看简介'}
          </button>
        </div>
      </div>

      {/* 医生服务 */}
      <div className="services-section">
        <h3 className="section-title">医生服务</h3>
        <div className="services-grid">
          <div className={`service-item ${doctor.services.onlineConsultation ? 'active' : 'disabled'}`}>
            <div className="service-icon online-consultation">
              <span>💬</span>
            </div>
            <div className="service-info">
              <h4>在线咨询</h4>
              <p>1对1问医生</p>
            </div>
          </div>
          
          <div className={`service-item ${doctor.services.prescriptionRefill ? 'active' : 'disabled'}`}>
            <div className="service-icon prescription">
              <span>💊</span>
            </div>
            <div className="service-info">
              <h4>复诊开方</h4>
              <p>申请用药</p>
            </div>
          </div>
          
          <div className={`service-item ${doctor.services.preferredPharmacy ? 'active' : 'disabled'}`}>
            <div className="service-icon pharmacy">
              <span>👍</span>
            </div>
            <div className="service-info">
              <h4>优选药房</h4>
              <p>用心优选</p>
            </div>
          </div>
          
          <div className={`service-item ${doctor.services.clinicAppointment ? 'active' : 'disabled'}`}>
            <div className="service-icon clinic">
              <span>🏥</span>
            </div>
            <div className="service-info">
              <h4>门诊预约</h4>
              <p>未开通</p>
            </div>
          </div>
        </div>
      </div>

      {/* 评价列表 */}
      <div className="reviews-section">
        <div className="section-header">
          <h3 className="section-title">评价 ({doctor.reviews.length})</h3>
          <div className="header-actions">
            <button className="add-comment-btn" onClick={handleShowCommentForm}>
              + 写评价
            </button>
            <button className="view-more-btn">查看更多</button>
          </div>
        </div>
        
        {/* 评论统计信息 */}
        <div className="comments-stats">
          <span className="stats-text">
            共 {doctor.reviews.length} 条评价
            {(() => {
              const doctorKey = `doctor_comments_${doctor.name}`
              const savedComments = localStorage.getItem(doctorKey)
              if (savedComments) {
                try {
                  const parsedComments = JSON.parse(savedComments)
                  const defaultCommentIds = new Set(['1', '2']) // 默认评论的ID
                  const userComments = parsedComments.filter((c: any) => !defaultCommentIds.has(c.id))
                  if (userComments.length > 0) {
                    return ` • 其中 ${userComments.length} 条已保存到本地`
                  }
                } catch (error) {
                  console.error('解析评论统计失败:', error)
                }
              }
              return ''
            })()}
          </span>
        </div>
        
        {/* 评论表单 */}
        {showCommentForm && (
          <div className="comment-form-container">
            <div className="comment-form-header">
              <h4>写评价</h4>
              <button className="close-btn" onClick={handleHideCommentForm}>
                ×
              </button>
            </div>
            
            <div className="rating-section">
              <label>评分：</label>
              <div className="rating-input">
                {[1, 2, 3, 4, 5].map(star => (
                  <button
                    key={star}
                    className={`star-btn ${newComment.rating >= star ? 'active' : ''}`}
                    onClick={() => handleRatingChange(star)}
                  >
                    ⭐
                  </button>
                ))}
                <span className="rating-text">{newComment.rating}星</span>
              </div>
            </div>
            
            <div className="tags-section">
              <label>标签：</label>
              <div className="tags-input">
                {['态度非常好', '回复很及时', '语气很温和', '讲解很细致', '专业水平高'].map(tag => (
                  <button
                    key={tag}
                    className={`tag-btn ${newComment.tags.includes(tag) ? 'active' : ''}`}
                    onClick={() => handleTagToggle(tag)}
                  >
                    {tag}
                  </button>
                ))}
              </div>
            </div>
            
            <div className="content-section">
              <label>评价内容：</label>
              <textarea
                className="comment-input"
                placeholder="请分享您的就医体验..."
                value={newComment.content}
                onChange={(e) => setNewComment(prev => ({ ...prev, content: e.target.value }))}
                rows={4}
              />
            </div>
            
            <div className="form-actions">
              <button className="cancel-btn" onClick={handleHideCommentForm}>
                取消
              </button>
              <button 
                className="submit-btn"
                onClick={handleSubmitComment}
                disabled={!newComment.content.trim()}
              >
                提交评价
              </button>
              <button 
                className="clear-comments-btn"
                onClick={handleClearComments}
              >
                清理评论
              </button>
            </div>
          </div>
        )}
        
        <div className="reviews-list">
          {doctor.reviews.map((review) => (
            <div key={review.id} className="review-item">
              <div className="review-header">
                <span className="reviewer-name">{review.user}</span>
                <div className="rating">
                  {[...Array(review.rating)].map((_, i) => (
                    <span key={i} className="star">⭐</span>
                  ))}
                </div>
              </div>
              
              <div className="review-tags">
                {review.tags.map((tag, index) => (
                  <span key={index} className="tag">{tag}</span>
                ))}
              </div>
              
              {/* 评论内容 */}
              <div className="review-content">
                {review.content || '用户没有留下具体评价内容'}
              </div>
              
              {review.reply && (
                <div className="doctor-reply">
                  {review.reply}
                </div>
              )}
              
                             <div className="review-footer">
                 <div className="review-timestamp">
                   {review.timestamp}
                 </div>
                 <button 
                   className="reply-btn"
                   onClick={() => handleReplyClick(review.id)}
                 >
                   回复
                 </button>
               </div>
               
               {/* 回复输入框 */}
               {activeReplyId === review.id && (
                 <div className="reply-input-container">
                   <textarea
                     className="reply-input"
                     placeholder="请输入回复内容..."
                     value={replyContent}
                     onChange={(e) => setReplyContent(e.target.value)}
                     rows={3}
                   />
                   <div className="reply-actions">
                     <button 
                       className="reply-submit-btn"
                       onClick={() => handleSubmitReply(review.id)}
                       disabled={!replyContent.trim()}
                     >
                       发送回复
                     </button>
                     <button 
                       className="reply-cancel-btn"
                       onClick={() => handleCancelReply()}
                     >
                       取消
                     </button>
                   </div>
                 </div>
               )}
            </div>
          ))}
        </div>

        {/* 咨询记录 */}
        <div className="consultation-records">
          {doctor.consultationRecords.map((record) => (
            <div key={record.id} className="consultation-item">
              <span className="consultation-user">{record.user}</span>
              订购了{doctor.name}医生的{record.service}
            </div>
          ))}
        </div>
      </div>

      {/* 底部操作按钮 */}
      <div className="bottom-action">
        <button className="send-message-btn" onClick={handleSendMessage}>
          发消息
        </button>
      </div>
    </div>
  )
}

export default Index
